package com.forfunnet.minjian.ui;

import android.net.Uri;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.forfunnet.minjian.MyApplication;
import com.forfunnet.minjian.R;
import com.forfunnet.minjian.message.Product;
import com.forfunnet.minjian.message.response.BaseResponse;
import com.forfunnet.minjian.message.response.ProductListResponse;
import com.forfunnet.minjian.rest.MyRestClient;
import com.forfunnet.minjian.rest.MyRestHelper;
import com.forfunnet.minjian.ui.adapter.AdsImagePagerAdapter;
import com.forfunnet.minjian.ui.view.AdsBannerView;
import com.forfunnet.minjian.ui.view.CircleImageView;
import com.forfunnet.minjian.utils.CommonUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.applidium.shutterbug.FetchableImageView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Lei on 2015/1/16.
 */
@EFragment(R.layout.fragment_home)
public class HomeFragment extends Fragment
{
    private static final int FETCH_LIMIT = 10;
    @App
    MyApplication mApp;

    @ViewById(R.id.list)
    PullToRefreshListView mListView;

    @Bean
    ActivityHelper mActivityHelper;

    AdsBannerView mAdsView;
    ListAdapter mAdapter;
    List<Product> mDataList = new ArrayList<Product>();

    @Click(R.id.search)
    void toSearchPage()
    {
        //SearchActivity_.intent(getActivity()).start();
    }

    @AfterViews
    void init ()
    {
        mAdapter = new ListAdapter();
        mAdsView    = (AdsBannerView)getActivity().getLayoutInflater().inflate(R.layout.fragment_home_banner, null);
        mAdsView.setOnAdsClickListener(new AdsImagePagerAdapter.OnAdsClickListener() {
            @Override
            public void onClick(Uri uri) {
                //TODO
            }
        });

        mListView.getRefreshableView().addHeaderView(mAdsView, null, false);

        View mFootView = getActivity().getLayoutInflater().inflate(R.layout.list_item_footer, null);
        mListView.getRefreshableView().addFooterView(mFootView, null, false);

        mListView.setMode(PullToRefreshBase.Mode.BOTH);
        mListView.setScrollingWhileRefreshingEnabled(false);
        mListView.getLoadingLayoutProxy(false, true).setPullLabel(getString(R.string.pullup_to_loadmore));
        mListView.getLoadingLayoutProxy(true, false).setPullLabel(getString(R.string.pulldown_to_refresh));
        mListView.getLoadingLayoutProxy(true, true).setRefreshingLabel(getString(R.string.pull_loading));
        mListView.getLoadingLayoutProxy(true, true).setReleaseLabel(getString(R.string.release_to_loadmore));

        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2(){
            @Override
            public void onPullDownToRefresh(PullToRefreshBase refreshView)
            {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel("最后更新时间：" + dateFormat.format(new Date()));
                loadMore(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase refreshView)
            {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel("最后更新时间：" + dateFormat.format(new Date()));
                loadMore(false);
            }
        });

        // 刷到底了
        mListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener(){
            @Override
            public void onLastItemVisible()
            {

            }
        });

        // 点击一个item
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position > 1) {
                    Product item = mDataList.get(position - 2);
                    ProductDetailActivity_.intent(getActivity()).mProductId(item.Id).start();
                }
            }
        });

        mListView.setAdapter(mAdapter);
        mListView.setRefreshing(false);
    }

    @Override
    public void onResume() {
        super.onResume();
        mAdsView.start();
    }

    @Override
    public void onPause() {
        super.onPause();
        mAdsView.stop();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            mAdsView.stop();
        }
        else {
            mAdsView.start();
        }
    }

    void loadMore (boolean refresh)
    {
        getData(refresh);
    }

    @Background
    void getData(boolean refresh)
    {
        int start = refresh ? 0 : mDataList.size();
        getDataResult(refresh, mApp.restClient().getProductList(start, FETCH_LIMIT,
                null, null, false));
    }

    @UiThread
    void getDataResult(boolean refresh, ProductListResponse resp)
    {
        mListView.onRefreshComplete();
        if (BaseResponse.hasError(resp))
        {
            mActivityHelper.showShortToast(BaseResponse.getErrorMessage(resp));
        }
        else
        {
            if (refresh)
            {
                mDataList.clear();
            }
            mDataList.addAll(resp.DataList);

            mAdapter.notifyDataSetChanged();

            if (resp.DataList.size() < FETCH_LIMIT)
            {
                mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
            }
            else
            {
                mListView.setMode(PullToRefreshBase.Mode.BOTH);
            }
        }
    }

    @Background
    void onAttention (View view)
    {
        Product product = (Product)view.getTag();
        BaseResponse resp = null;
        if (product.IsFavorite)
        {
            resp = mApp.restClient().removeProductFavorite(product.Id);
        }
        else
        {
            resp = mApp.restClient().addProductFavorite(product.Id);
        }
        onAttentionResult(resp, product, view);
    }

    @UiThread
    void onAttentionResult (BaseResponse resp, Product product, View view)
    {
        if(resp == null)
            return;

        if (BaseResponse.hasError(resp))
        {
            if (resp.ResponseStatus.Message != null)
            {
                mActivityHelper.showShortToast(resp.ResponseStatus.Message);
            }
            else
            {
                mActivityHelper.showShortToast("关注/取消关注操作异常，请重试");
            }
        }
        else
        {
            product.IsFavorite = !product.IsFavorite;
            ImageView attentionBtn = (ImageView)view;
            if (product.IsFavorite)
            {
                attentionBtn.setImageResource(R.drawable.attentioned);
            }
            else
            {
                attentionBtn.setImageResource(R.drawable.disattention);
            }
        }
    }

    public class ListAdapter extends BaseAdapter
    {
        public final class ListItemView
        {
            FetchableImageView  cover;
            CircleImageView headImage;
            ImageView concernImage;
            TextView name;
            TextView title;

            ListItemView(View root)
            {
                cover = (FetchableImageView)root.findViewById(R.id.cover);
                headImage = (CircleImageView) root.findViewById(R.id.head_image);
                concernImage = (ImageView) root.findViewById(R.id.concern_image);
                name = (TextView) root.findViewById(R.id.name);
                title = (TextView) root.findViewById(R.id.content);

                concernImage.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onAttention(v);
                    }
                });
            }

            void setData(Product product)
            {
                cover.setImage(MyRestHelper.ProductImageUrl(mApp.restClient(), product.Id));
                headImage.setImage(MyRestHelper.UserImageHeadUrl(mApp.restClient(), product.OwnerId));
                name.setText(product.OwnerId == 0 ? getString(R.string.official) : product.OwnerName);
                title.setText(product.Name);
                concernImage.setImageResource(product.IsFavorite ? R.drawable.attentioned : R.drawable.disattention);
                concernImage.setTag(product);
            }
        }

        @Override
        public int getCount()
        {
            return mDataList.size();
        }

        @Override
        public Object getItem(int position)
        {
            return mDataList.get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            ListItemView listItemView = null;
            if (convertView == null)
            {
                convertView = HomeFragment.this.getActivity().getLayoutInflater().inflate(R.layout.list_item_home_product, null);

                listItemView = new ListItemView(convertView);
                convertView.setTag(listItemView);
            }
            else
            {
                listItemView = (ListItemView) convertView.getTag();
            }

            Product item = mDataList.get(position);
            listItemView.setData(item);

            return convertView;
        }
    }
}
